<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="循证医学数据" prop="evidenceBasedContent">
        <el-input
          v-model="queryParams.evidenceBasedContent"
          placeholder="请输入循证医学数据"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类别" prop="evidenceCategory">
        <el-select
          v-model="queryParams.evidenceCategory"
          placeholder="请选择类别"
          clearable
          :style="{ width: '100%' }"
        >
          <el-option
            v-for="(item, index) in guardianLevel"
            :key="index"
            :label="item.dictLabel"
            :value="item.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['workstation:evidenceBasedMedicine:add']"
          >新增</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="evidenceBasedMedicineList"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column
        label="循证医学数据"
        align="center"
        prop="evidenceBasedContent"
      />
      <el-table-column label="类别" align="center" prop="evidenceCategoryStr" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row)"
            v-if="scope.row.ossUrl"
            v-hasPermi="['system:oss:download']"
            >下载</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleLook(scope.row)"
            v-hasPermi="['workstation:evidenceBasedMedicine:query']"
            icon="el-icon-view"
            v-if="panduan(scope.row.ossUrl)"
            >预览</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['workstation:evidenceBasedMedicine:edit']"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['workstation:evidenceBasedMedicine:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或编辑循证医学相关数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
        :disabled="disabled"
      >
        <el-form-item label="循证医学数据">
          <el-input
            type="textarea"
            :rows="6"
            clearable
            placeholder="请输入循证医学数据"
            v-model="form.evidenceBasedContent"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="类别" prop="evidenceCategory">
          <el-select
            v-model="form.evidenceCategory"
            placeholder="请选择类别"
            clearable
            :style="{ width: '100%' }"
          >
            <el-option
              v-for="(item, index) in guardianLevel"
              :key="index"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传附件">
          <fileUpload
            @input="editOSSID"
            v-model="form.file"
            :limit="1"
            :fileSize="1024"
            :fileType="['doc', 'docx', 'pdf']"
            acceptType=".doc,.docx,.pdf"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <template v-if="title == '查看循证医学相关数据'">
          <el-button @click="() => (open = false)">取 消</el-button>
        </template>
        <template v-else>
          <el-button :loading="buttonLoading" type="primary" @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </template>
      </div>
    </el-dialog>
    <el-dialog title="预览" :visible.sync="dialogVisible" width="90%">
      <div v-loading="wordloading" style="height: 100%; width: 100%">
        <iframe
          v-if="form.type == 'pdf'"
          ref="pdfViewer"
          id="previewPdf"
          :src="form.ossUrl"
          width="100%"
          height="810px"
        >
        </iframe>
        <iframe
          v-if="form.type == 'docx' || form.type == 'doc'"
          ref="pdfViewer"
          id="previewPdf"
          :src="form.ossUrl"
          width="100%"
          height="810px"
        >
        </iframe>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listEvidenceBasedMedicine,
  getEvidenceBasedMedicine,
  delEvidenceBasedMedicine,
  addEvidenceBasedMedicine,
  updateEvidenceBasedMedicine,
} from "@/api/workstation/evidenceBasedMedicine";
import { download } from "@/api/workstation/clinicHandbook";

export default {
  name: "EvidenceBasedMedicine",
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 循证医学相关数据表格数据
      evidenceBasedMedicineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        evidenceBasedContent: undefined,
        evidenceCategory: undefined,
        ossId: undefined,
        ossUrl: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "循证医学ID不能为空", trigger: "blur" },
        ],
        evidenceBasedContent: [
          { required: true, message: "循证医学数据不能为空", trigger: "blur" },
        ],
        ossId: [{ required: true, message: "附件ID不能为空", trigger: "blur" }],
        ossUrl: [
          { required: true, message: "附件地址不能为空", trigger: "blur" },
        ],
      },
      guardianLevel: [], // 循证类别数组
      disabled: false, // 弹窗表单是否禁用
      dialogVisible: false, // 预览弹窗
      wordloading: true, // 预览弹窗 加载状态
    };
  },
  created() {
    this.getList();
    this.getDicts("evidence_category").then((res) => {
      this.guardianLevel = res.data;
    });
  },
  methods: {
    panduan(url) {
      if (!url) return;
      if (url.lastIndexOf(".pdf") === url.length - 4) {
        return true;
      } else {
        return false;
      }
    },
    /** 查询循证医学相关数据列表 */
    getList() {
      this.loading = true;
      listEvidenceBasedMedicine(this.queryParams).then((response) => {
        this.evidenceBasedMedicineList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        evidenceBasedContent: undefined,
        evidenceCategory: undefined,
        ossId: undefined,
        ossUrl: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.disabled = false;
      this.reset();
      this.open = true;
      this.title = "添加循证医学相关数据";
    },
    /** 编辑按钮操作 */
    handleUpdate(row) {
      this.disabled = false;
      this.loading = true;
      this.reset();
      const id = row.id || this.ids;
      getEvidenceBasedMedicine(id).then((response) => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "编辑循证医学相关数据";
      });
    },
    /** 查看按钮操作 */
    async handleLook(row) {
      if (!row.ossUrl) {
        this.$modal.msgError("预览失败，请重新上传文件后再试~");
        return;
      }
      if (row.ossUrl.lastIndexOf(".docx") === row.ossUrl.length - 5) {
        this.form = row;
        this.form.type = "docx";
        const encodedString = encodeURIComponent(this.form.ossUrl);
        this.form.ossUrl =
          "https://view.officeapps.live.com/op/view.aspx?src=" + encodedString;
        this.wordloading = false;
      } else if (row.ossUrl.lastIndexOf(".doc") === row.ossUrl.length - 4) {
        this.form = row;
        this.form.type = "doc";
        this.form.ossUrl =
          "https://view.officeapps.live.com/op/view.aspx?src=" + encodedString;
        this.wordloading = false;
      } else if (row.ossUrl.lastIndexOf(".pdf") === row.ossUrl.length - 4) {
        const res = await download(row.ossId);
        const blob = new Blob([res], {
          type: "application/pdf", //data 服务器返回的二进制数据流
        });
        const url = window.URL.createObjectURL(blob); //将文件转为路径
        window.open(
          "/static/pdfjs-2.5.207-es5-dist/web/viewer.html?file=" + url + "&.pdf"
        );
      } else {
        this.wordloading = false;
      }
    },
    /** 下载按钮操作 */
    handleDownload(row) {
      if (!row.ossId) {
        this.$modal.msgError("暂无附件,下载失败");
        return;
      }
      this.$download.oss(row.ossId);
    },
    editOSSID(data) {
      if (data) {
        this.form.ossId = data[0].ossId;
        this.form.ossUrl = data[0].url;
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateEvidenceBasedMedicine(this.form)
              .then((response) => {
                this.$modal.msgSuccess("编辑成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addEvidenceBasedMedicine(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm(
          `是否确认删除 ${row.createBy} 创建的 ${row.evidenceBasedContent} 循证医学相关数据项？`
        )
        .then(() => {
          this.loading = true;
          return delEvidenceBasedMedicine(ids);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "workstation/evidenceBasedMedicine/export",
        {
          ...this.queryParams,
        },
        `evidenceBasedMedicine_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog:not(.is-fullscreen) {
  margin-top: 1vh !important;
}
::v-deep .el-dialog__body {
  // padding: 5px 10px;
  height: 810px;
  color: #606266;
  font-size: 14px;
  word-break: break-all;
  overflow: scroll;
}
::v-deep .el-dialog__header {
  padding: 10px;
  padding-bottom: 10px;
}
::v-deep .el-dialog__footer {
  padding: 10px;
  text-align: right;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}
::v-deep #container .docx-wrapper {
  overflow: scroll !important;
  background: white !important;
  padding: 0;
}
.docx {
  width: 100% !important;
  padding: 0rem !important;
  min-height: auto !important;
  box-shadow: none;
  margin-bottom: 0;
}
</style>
